//
//  LoginViewController.m
//  leo
//
//  Created by 常艳 on 15/9/13.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "SyncManager.h"
#import "DataManager.h"
#import "BindViewController.h"
#import "LocationViewController.h"
#import "ChatListViewController.h"
#import "GrowthViewController.h"
#import "ManagerViewController.h"
#import "MainPageViewController.h"
#import "SetBabyInfoViewController.h"
#import "ResetPassViewController.h"
#import "AppDelegate.h"
#import <MAMapKit/MAMapKit.h>
@interface LoginViewController ()
@property(nonatomic,strong) SyncManager *syncManager;
@property (nonatomic,strong) Reachability *internetReachability;
@property(nonatomic,assign) BOOL is_getManager;
@property(nonatomic,strong) DataManager *dataManager;
@property(nonatomic,weak) AppDelegate *mydelegate;
@end

@implementation LoginViewController
-(void)dealloc
{
    [self removeObservers];
    self.syncManager=NULL;
    self.internetReachability=NULL;
    self.dataManager=NULL;
    self.mydelegate=NULL;
}
-(void)registerObservers
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:ENTERFOREGROUND object:nil];
    
}
-(void)removeObservers
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:ENTERFOREGROUND object:nil];
}
- (void)receiveNotification:(NSNotification *)sender {
    if(self.phone.isFirstResponder)
    {
        [self.phone resignFirstResponder];
        [self.phone becomeFirstResponder];
    }
    if(self.pass.isFirstResponder)
    {
        [self.pass resignFirstResponder];
        [self.pass becomeFirstResponder];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars=YES;
    self.title=@"账号登陆";
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"注册" style:UIBarButtonItemStyleDone target:self action:@selector(registerUser)];
    [self.navigationItem setRightBarButtonItem:rightButton];
    rightButton=NULL;
    // Do any additional setup after loading the view from its nib.
    self.is_getManager=YES;
    float x=self.phone.frame.size.height;
    UIView *phoneleftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 20, x)];
    self.phone.leftView=phoneleftView;
    self.phone.leftViewMode=UITextFieldViewModeAlways;
    UIView *passleftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 20,x)];
    self.pass.leftView=passleftView;
    self.pass.leftViewMode=UITextFieldViewModeAlways;

    [self registerObservers];
    /*
    //注册网络状态变化通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name: kReachabilityChangedNotification
                                               object: nil];
    self.internetReachability = [Reachability reachabilityForInternetConnection];
    if(self.internetReachability!=NULL)
    {
        [self.internetReachability startNotifier];
    }
    */
    self.mydelegate=[[UIApplication sharedApplication] delegate];
    self.dataManager=[[DataManager alloc] init];
    if(self.dataManager==NULL)
    {
        [self showErrorMsg:@"程序发生错误，code is 29"];
        return;
    }
    self.syncManager=[[SyncManager alloc] init];
    if(self.syncManager==NULL)
    {
        NSLog(@"%@,login,syncManager is null",Login_Tag);
        [self showErrorMsg:@"程序发生错误，code is 30"];
        return;
    }
    NSString *accountName=[Tooler getAccountName];
    if(accountName!=NULL&&![accountName isEqualToString:@"(null)"]&&![accountName isEqualToString:@""])
    {
        self.phone.text=accountName;
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)registerUser {
    RegisterViewController *registViewController=[[RegisterViewController alloc]init];
    registViewController.type=0;
    [self.navigationController pushViewController:registViewController animated:YES];
}
- (IBAction)login:(id)sender {    
    [self.phone resignFirstResponder];
    [self.pass resignFirstResponder];
     self.loginBtn.enabled=NO;
    [self.indicator startAnimating];
     NSString *phone=[self.phone text];
     NSString *pass=[self.pass text];
    phone=[phone stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    pass=[pass stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([phone isEqualToString:@"305305305"]) {
//  #define hostName @"test.apis.atlasyun.net"
//  #define socketHost @"test.push.atlasyun.net"
//  #define socketPort @"9000"
    }
    if(phone==NULL||[phone length]==0)
    {
        [self showErrorMsg:@"手机号不能为空"];
        return;
    }
    if([phone length]!=11||[Tooler checkStringBegin:phone]==NO)
    {
        [self showErrorMsg:@"用户名不存在"];
        return;
    }
    if(pass==NULL||[pass length]==0)
    {
        [self showErrorMsg:@"密码不能为空"];
        return;
    }
    if([pass length]<6)
    {
        [self showErrorMsg:@"密码错误"];
        return;
    }
  
    NSLog(@"%@,login,phone is %@, pass is %@",Login_Tag,phone,pass);
    //调用API登录
    [self.syncManager loginPhone:phone pass:pass completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        if(self.dataManager!=NULL)
            [self.dataManager getActiveUser];
        [self loginCallback:result retValue:retValue description:description];
    }];
}
- (IBAction)backgroundTap:(id)sender {
    [self.phone resignFirstResponder];
    [self.pass resignFirstResponder];
}
-(void)showErrorMsg:(NSString *)msg
{
    [self.indicator stopAnimating];
    self.loginBtn.enabled=YES;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
-(void)loginCallback:(SyncResult) result retValue:(NSDictionary *)ret description:(NSString *)description
{

    if(result==SUCESS)
    {
        dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        if(queue!=NULL)
        {
            dispatch_async(queue, ^{
                [self syncUserInfo];
            });
        }
        if(self.mydelegate!=NULL)
        {
            /*
            NSData *dataMsg=[self.mydelegate getLinkMsg:PT_SETUP_LINK];
            if(dataMsg!=NULL)
            {
                [self.mydelegate sendMsg:dataMsg];
            }*/
            self.mydelegate.islogin=YES;
            [self.mydelegate connectToTcp];
        }
        //获取账号的所有手表
        [self.syncManager getBoundDevices:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            [self.indicator stopAnimating];
            self.loginBtn.enabled=YES;
            if(result==SUCESS)
            {
                  NSLog(@"%@,getBoundDevices,success",Login_Tag);
                User *user=[User sharedSingleton];
                if(user==NULL)
                {
                    [self showErrorMsg:@"程序发生错误,,code is 31"];
                    return ;
                }
                if(retValue!=NULL&&[[retValue valueForKey:@"watchCount"] intValue]<0)
                {
                    //没有绑定手表，跳到绑定界面
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    BindViewController *bindView=[[BindViewController alloc] init];
                    UINavigationController *bindNavigationController = [[UINavigationController alloc] initWithRootViewController:bindView];
                    if(self.mydelegate!=NULL)
                        [self.mydelegate setNavProperty:bindNavigationController];
                    self.view.window.rootViewController = bindNavigationController;
                    bindView=NULL;
                }
                else
                {
                    Watch *watch=NULL;
                    if(self.dataManager!=NULL)
                    {
                        watch=[self.dataManager getActiveWatch:user.uid];
                    }
                    if(watch==NULL)
                    {
                        [self showErrorMsg:@"没有选中手表，code is 2"];
                        return;
                    }
                    if(watch.role==1)
                        self.mydelegate.isAdmin=YES;
                    else
                        self.mydelegate.isAdmin=NO;
                    if(watch!=NULL&&watch.deviceUid!=NULL&&watch.nickname!=NULL&&![watch.nickname isEqualToString:@"(null)"]&&![watch.nickname isEqualToString:@""])
                    {
                        //已设置宝宝信息，跳转到主界面
                        [self.navigationController popToRootViewControllerAnimated:YES];
                        NSMutableArray *items = [[NSMutableArray alloc]init];
                        CGRect rect = [UIScreen mainScreen].bounds;
                        self.mydelegate.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 20+44, rect.size.width, rect.size.height-(20+44))];
                        self.mydelegate.search = [[AMapSearchAPI alloc] init];
                        BaseMapViewController *locationViewController = [[LocationViewController alloc]init];
                        [items addObject:locationViewController];
                        
                        ChatListViewController *chatViewController = [[ChatListViewController alloc]init];
                        [items addObject:chatViewController];
                        
                        
                        GrowthViewController *growthViewController = [[GrowthViewController alloc]init];
                        [items addObject:growthViewController];
                        
                        ManagerViewController *managerViewController = [[ManagerViewController alloc]init];
                        [items addObject:managerViewController];
                        
                        
                        MainPageViewController *mainPageViewController = [[MainPageViewController alloc]init];
                        [mainPageViewController setViewControllers:items];
                        locationViewController.motherTabViewController = mainPageViewController;
                        managerViewController.motherTabViewController=mainPageViewController;
                        growthViewController.motherTabViewController=mainPageViewController;
                        UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:mainPageViewController];
                        if(self.mydelegate!=NULL)
                            [self.mydelegate setNavProperty:nav];
                        mainPageViewController.extendedLayoutIncludesOpaqueBars=YES;
                         self.view.window.rootViewController=nav;


                    }
                    else
                    {
                        //跳转到设置宝宝信息界面
                        [self.navigationController popToRootViewControllerAnimated:YES];
                        SetBabyInfoViewController *setBabyView=[[SetBabyInfoViewController alloc] init];
                        setBabyView.watch=watch;
                        UINavigationController *babyNav=[[UINavigationController alloc] initWithRootViewController:setBabyView];
                        if(self.mydelegate!=NULL)
                            [self.mydelegate setNavProperty:babyNav];
                        setBabyView=NULL;
                        self.view.window.rootViewController=babyNav;
                        setBabyView=NULL;

                        
                    }
                    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                    if(queue==NULL)
                    {
                        NSLog(@"%@,applicationWillEnterForeground,queue is null",DATAMANAGER_TAG);
                        return;
                    }
                    dispatch_async(queue, ^{
                        //另开一个线程去获取手表的所有管理员
                        [self syncManagers];
                        //[self syncContacts];
                    });

                   
                }
            }
            else
            {
                NSLog(@"%@,getBoundDevices,fail",Login_Tag);
                self.is_getManager=NO;
                if(result==NODATA)
                {
                    [self showErrorMsg:@"当前网络异常，请检查网络"];
                }
                else
                {
                    if(description!=NULL)
                        [self showErrorMsg:description];
                    else
                        [self showErrorMsg:@"程序发生错误，,code is 32"];
                }
            }
        }];
    }
    else
    {
       NSLog(@"%@,loginCallback,fail",Login_Tag);
        if(result==NODATA)
        {
            [self showErrorMsg:@"当前网络异常，请检查网络"];
        }
        else
        {
            if(description!=NULL)
                [self showErrorMsg:description];
            else
                [self showErrorMsg:@"登录失败"];
        }

    }
}
-(void)syncUserInfo
{
    if(self.syncManager==NULL)
    {
        NSLog(@"%@,syncUserInfo,syncManager is null.",Login_Tag);
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        [self showErrorMsg:@"程序发生错误，code is 33"];
        return;
    }
    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    if(queue==NULL)
    {
        NSLog(@"%@,applicationWillEnterForeground,queue is null",DATAMANAGER_TAG);
        return;
    }
    dispatch_async(queue, ^{
        [self.syncManager getUserInfo:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            
        }];
    });

}
-(void)syncManagers
{
    if(self.syncManager==NULL)
    {
        NSLog(@"%@,syncManagers,syncManager is null.",Login_Tag);
        return;
    }
    if(self.dataManager==NULL)
    {
        NSLog(@"%@,syncManagers,dataManager is null.",Login_Tag);
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        [self showErrorMsg:@"程序发生错误，code is 34"];
        return;
    }
    @try {

                NSArray *watchLists=[self.dataManager getWatchList:user.uid];
                if(watchLists==NULL||[watchLists count]==0)
                {
                    NSLog(@"%@,syncManagers,watchLists is null.",Login_Tag);
                    return ;
                }
                for(int i=0;i<[watchLists count];i++)
                {
                    Watch *watch=[watchLists objectAtIndex:i];
                    if(watch==NULL)
                    {
                        NSLog(@"%@,syncManagers,watch is null.",Login_Tag);
                        continue;
                    }
                    [self.syncManager getBoundUsers:watch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                        if(result==SUCESS)
                        {

                        }
                        else
                        {
                            
                        }
                    }];

                    
                }

    }
    @catch (NSException *exception) {
        NSLog(@"%@,syncManagers,exception is %@.",Login_Tag,[exception reason]);
    }

}

-(void)syncContacts
{
    if(self.syncManager==NULL)
    {
        NSLog(@"%@,syncContacts,syncManager is null.",Login_Tag);
        return;
    }
    if(self.dataManager==NULL)
    {
        NSLog(@"%@,syncManagers,dataManager is null.",Login_Tag);
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        [self showErrorMsg:@"程序发生错误，code is 35"];
        return;
    }
    @try {

                NSArray *watchLists=[self.dataManager getWatchList:user.uid];
                if(watchLists==NULL||[watchLists count]==0)
                {
                    NSLog(@"%@,syncContacts,watchLists is null.",Login_Tag);
                    return ;
                }
                for(int i=0;i<[watchLists count];i++)
                {
                    Watch *watch=[watchLists objectAtIndex:i];
                    if(watch==NULL)
                    {
                        NSLog(@"%@,syncContacts,watch is null.",Login_Tag);
                        continue;
                    }
                    [self.syncManager getWatchContact:watch.deviceUid completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                        if(result==SUCESS)
                        {

                        }
                        else
                        {

                        }
                    }];
                    
                }
                
        
    }
    @catch (NSException *exception) {
        
    }
    
}

- (IBAction)forgetPwd:(id)sender {
    ResetPassViewController *repassViewController=[[ResetPassViewController alloc]init];
    [self.navigationController pushViewController:repassViewController animated:YES];
}
/*
- (void)reachabilityChanged:(NSNotification *)note {
    NSLog(@"%@,reachabilityChanged entered",Login_Tag);
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    NetworkStatus status = [curReach currentReachabilityStatus];
    if(self.is_getManager==NO)
    {
        if(status!=NotReachable)
        {
            self.is_getManager=YES;
            [self syncManagers];
        }
    }
    
}*/
- (IBAction)phoneTextFieldChange:(id)sender {
    if(self.phone.text.length>20)
        self.phone.text=[self.phone.text substringToIndex:20];
    self.phone.text=[Tooler validateNumber:self.phone.text];
}

- (IBAction)passTextFieldChange:(id)sender {
    if(self.pass.text.length>20)
        self.pass.text=[self.pass.text substringToIndex:20];
}


@end
